<template>
  <div>
    <el-switch
      v-model="dragSwitch"
      active-color="#13ce66"
      inactive-color="#ff4949"
      active-text="开启拖拽功能"
      inactive-text="关闭拖拽功能"
    >
    </el-switch>
    <el-button type="danger" @click="deleteNodes">批量删除</el-button>
    <el-tree
      :data="menus"
      :props="defaultProps"
      :expand-on-click-node="false"
      show-checkbox
      node-key="catId"
      :default-expanded-keys="defaultExpandNode"
      :draggable="dragSwitch"
      :allow-drop="allowDrop"
      @node-drop="handleDrop"
      ref="menuTree"
    >
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <!--只有1、2级节点才可以追加节点 -->
          <el-button
            v-if="data.catLevel == 1 || data.catLevel == 2"
            type="text"
            size="mini"
            @click="() => append(data)"
          >
            Append
          </el-button>
          <!-- 节点没有子节点时才可以删除 -->
          <!-- node存储节点信息，data存储节点的menus部分信息 -->
          <el-button
            v-if="node.childNodes.length == 0"
            type="text"
            size="mini"
            @click="() => remove(node, data)"
          >
            Delete
          </el-button>

          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
        </span>
      </span>
    </el-tree>

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
    >
      <!-- :model 表单绑定的对象 -->
      <el-form :model="category" :inline="true">
        <el-form-item label="分类名称">
          <el-input v-model="category.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类图标">
          <el-input
            v-model="category.productUnit"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="分类库存">
          <el-input
            v-model="category.productCount"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="methodPoint">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    return {
      dragSwitch: false,
      //append对话框绑定对象
      category: {},
      categoryList: [],
      //菜单信息
      menus: [],
      maxLevel: 0,
      dialogVisible: false,
      //用来区分对话框的操作类型，menu=[add,edit];
      operType: "",
      //默认展开节点
      defaultExpandNode: [],
      defaultProps: {
        children: "children",
        label: "name",
      },
    };
  },

  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    //批量删除
    deleteNodes() {
      //被选中的所有节点
      let seleted = this.$refs.menuTree.getCheckedNodes();
      console.log("被选中删除的节点：", seleted);
      //收集节点的id
      let deleteCatIds = [];
      let deleteNames = [];
      let len = seleted.length;
      for (let i = 0; i < len; i++) {
        deleteCatIds.push(seleted[i].catId);
        deleteNames.push(seleted[i].name);
      }
      console.log("catids=", deleteCatIds);
      console.log("deleteNames=", deleteNames);
      //确认提示框
      this.$confirm(`是否删除【${deleteNames}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/category/delete/patch"),
            method: "post",
            data: this.$http.adornData(deleteCatIds, false),
          }).then(({ data }) => {
            this.$message({
              message: "删除菜单成功",
              type: "success",
            });
            //刷新页面
            this.getEnums();
          });
        })
        .catch(() => {});
    },
    //参数
    //draggingNode：被拖拽的节点
    //dropNode:     拖拽放置的位置的参照节点
    //type：        被拖拽的节点在参照节点的位置关系[prev,next,inner]
    //ev:           事件对象
    handleDrop(draggingNode, dropNode, type, ev) {
      this.categoryList = [];
      console.log("进入handleDrop函数", draggingNode, dropNode, type);
      if (type == "inner") {
        //内置时，变动节点parentId=参照节点data.cid
        let nodeParentCid = dropNode.data.catId;
        //内置时更新排序，取出参照节点的子节点列表并遍历，全量更新节点排序，并对变动节点做特殊处理(改变parentId)
        let length = dropNode.childNodes.length;
        for (let i = 0; i < length; i++) {
          if (dropNode.childNodes[i].data.catId == draggingNode.data.catId) {
            dropNode.childNodes[i].data.parentCid = nodeParentCid;
          }
          this.categoryList.push({
            catId: dropNode.childNodes[i].data.catId,
            sort: i,
            catLevel: dropNode.data.catLevel * 1 + 1,
            parentCid: nodeParentCid,
            // name: dropNode.childNodes[i].data.name,
          });
          //更新变动节点的子节点的层级信息
          this.updateNodeLevel(draggingNode.data);
        }
      } else {
        //平行变动时,变动节点的parentId=参照节点parentId
        let nodeParentCid = dropNode.data.parentCid;
        //需要全量更新参照节点的parent节点的ChildNodes
        console.log("length", dropNode.parent.childNodes);
        let length = dropNode.parent.childNodes.length;
        for (let i = 0; i < length; i++) {
          if (dropNode.parent.childNodes[i].catId == draggingNode.data.catId) {
            dropNode.parent.childNodes[i].parentCid = nodeParentCid;
          }
          this.categoryList.push({
            catId: dropNode.parent.childNodes[i].data.catId,
            sort: i,
            catLevel: dropNode.data.catLevel * 1,
            parentCid: nodeParentCid,
            // name: dropNode.parent.data[i].name,
          });
        }
        //如果变动节点与参照节点的level不一致，需要更新变动节点的子节点的层级信息
        console.log(
          "层级一致性：",
          draggingNode.data.catLevel == dropNode.data.catLevel
        );
        if (draggingNode.data.catLevel != dropNode.data.catLevel) {
          this.updateNodeLevel(draggingNode.data);
        }
      }
      //发送
      console.log("需要改变的节点信息：", this.categoryList);

      this.$http({
        url: this.$http.adornUrl("/product/category/update/patch"),
        method: "post",
        data: this.$http.adornData(this.categoryList, false),
      }).then(({ data }) => {
        console.log("ajax response success", this.categoryList);
        //弹出消息框
        this.$message({
          message: "编辑菜单成功",
          type: "success",
        });
        //重置容器
        this.categoryList = [];
        //更改列表后刷新列表
        this.getEnums();
        //打开编辑的菜单
        this.defaultExpandNode = [dropNode.data.catId];
      });
    },
    //传入一个节点，更正该节点的子节点的层级信息
    updateNodeLevel(node) {
      if (node.children != null && node.children.length > 0) {
        //根结点的层级
        let rootLevel = node.catLevel;
        for (let i = 0; i < node.children.length; i++) {
          //将更正的信息提交到容器中
          console.log("更正子节点信息:", node.children[i]);
          this.categoryList.push({
            catId: node.children[i].catId,
            catLevel: rootLevel * 1 + 1,
            // name: node.children[i].name,
          });
          //递归调用
          this.updateNodeLevel(node.children[i]);
        }
      }
    },
    //参数
    //draggingNode：被拖拽的节点
    //dropNode:     拖拽放置的位置的参照节点
    //type：        被拖拽的节点在参照节点的位置关系[prev,next,inner]
    allowDrop(draggingNode, dropNode, type) {
      console.log("进入allowDrop方法", draggingNode, dropNode, type);
      this.getNodeDeep(draggingNode.data);
      //deep: 被拖拽节点到最大深度的深度(即去掉父节点的深度)
      var deep = this.maxLevel - draggingNode.data.catLevel + 1;

      //往里面放,deep+参照节点level<=3
      if (type == "inner") {
        return deep + dropNode.data.catLevel <= 3;
      } else {
        //往前后放，deep+参照节点level-1<=3
        return deep + dropNode.data.catLevel - 1 <= 3;
      }
    },

    //传入一个节点，获取节点中的最大深度
    getNodeDeep(node) {
      if (node.children != null && node.children.length > 0) {
        for (let i = 0; i < node.children.length; i++) {
          if (node.children[i].catLevel > this.maxLevel) {
            this.maxLevel = node.children[i].catLevel;
          }
          this.getNodeDeep(node.children[i]);
        }
      }
    },

    getEnums() {
      this.$http({
        url: this.$http.adornUrl("/product/category/list/tree"),
        method: "get",
      }).then(({ data }) => {
        this.menus = data.data;
        console.log(this.menus);
      });
    },
    //方法指针，用于判断对话框提交的操作类型
    methodPoint() {
      if (this.operType == "add") {
        this.addCategory();
      }
      if (this.operType == "edit") {
        this.editCategory();
      }
    },
    append(data) {
      this.operType = "add";
      this.dialogVisible = true;
      //对category对象赋值
      this.category = {
        name: "",
        parentCid: data.catId,
        catId: null,
        productUnit: null,
        productCount: null,
        catLevel: data.catLevel * 1 + 1,
        showStatus: 1,
        sort: 0,
      };
      console.log("append", data);
    },

    edit(data) {
      //清空选项卡缓存
      (this.category = {}),
        //不使用缓存数据，从数据库查询
        this.$http({
          url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
          method: "get",
        }).then(({ data }) => {
          console.log("response", data);
          this.category = {
            name: data.data.name,
            productUnit: data.data.productUnit,
            productCount: data.data.productCount,
            catId: data.data.catId,
            parentCid: data.data.parentCid,
          };
          console.log("数据库获取的回显数据1", this.category);
        });

      this.operType = "edit";
      this.dialogVisible = true;
    },

    addCategory() {
      this.$http({
        url: this.$http.adornUrl("/product/category/save"),
        method: "post",
        data: this.$http.adornData(this.category, false),
      }).then(({ data }) => {
        //成功提示消息框
        this.$message({
          message: "新增菜单成功",
          type: "success",
        });

        //更改列表后刷新列表
        this.getEnums();
        //关闭消息框，并重置数据

        this.defaultExpandNode = [this.category.parentCid];
        this.category = {};
        this.dialogVisible = false;
      });
    },

    editCategory() {
      //只发送有可能修改的数据与ID标识
      var { catId, name, productUnit, productCount } = this.category;
      var segment = {
        catId: catId,
        name: name,
        productUnit: productUnit,
        productCount: productCount,
      };
      this.$http({
        url: this.$http.adornUrl("/product/category/update"),
        method: "post",
        data: this.$http.adornData(segment, false),
      }).then(({ data }) => {
        //成功提示消息框
        this.$message({
          message: "编辑菜单成功",
          type: "success",
        });

        //更改列表后刷新列表
        this.getEnums();
        //关闭消息框，并重置数据,打开操作的选项卡
        this.defaultExpandNode = [this.category.parentCid];
        this.category = {};
        this.dialogVisible = false;
      });
    },

    remove(node, data) {
      //确认弹窗
      this.$confirm(`是否删除【${data.name}】菜单?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var ids = [data.catId];
          this.$http({
            url: this.$http.adornUrl("/product/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false),
          }).then(({ data }) => {
            //成功提示消息框
            this.$message({
              message: "菜单删除成功",
              type: "success",
            });
            //保留菜单的展开信息
            this.defaultExpandNode = [node.parent.data.catId];
            //更改列表后刷新列表
            this.getEnums();
          });
        })
        .catch(() => {
          this.$message({
            //规范要求保留
          });
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getEnums();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共 css 类
</style>